package cn.itsource.user.controller;

import cn.itsource.base.exception.BusinessException;
import cn.itsource.user.domain.LoginInfo;
import cn.itsource.user.domain.User;
import cn.itsource.user.service.ILoginInfoService;
import cn.itsource.util.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
public class LoginController {

    @Autowired
    private ILoginInfoService loginInfoService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/login")
    public AjaxResult login(@RequestBody User user){
        System.out.println(user);
        try {
            //获取当前的登录用户信息
            LoginInfo loginInfo= loginInfoService.login(user);
            //生成token
            String token = UUID.randomUUID().toString();
            //把当前用户和token 放到redis里面  并设置有效期是30分钟
            redisTemplate.opsForValue().set(token,loginInfo,30, TimeUnit.MINUTES);
            //把 token  登录用户 返回给前端
            Map<String,Object> map = new HashMap();
            map.put("TOKEN",token);
            //返回给前端以前 清空敏感数据
            loginInfo.setPassword(null);
            loginInfo.setSalt(null);

            map.put("loginInfo",loginInfo);
            return AjaxResult.me().setResultObj(map);
        } catch (BusinessException e) {
            return AjaxResult.me().setMessage(e.getMessage());
        }

    }
}
